const System = require('../../domain/system/system')
const Usecase = require('../../shared/usecase/Usecase')
const { SystemCodeExistError } = require('../../domain/system/error')

class CreateSystem extends Usecase {
  constructor({ systemRepo, database, currentUser }) {
    super()
    this.systemRepo = systemRepo
    this.sequelize = database.sequelize
    this.currentUser = currentUser
  }
  async _validate(entity) {
    await entity.validate()
    const system = await this.systemRepo.findByCode(entity.code)
    if (system) throw new SystemCodeExistError()
  }
  async execute(data) {
    const system = System.create(data)
    await this._validate(system)
    const transaction = await this.sequelize.transaction()
    try {
      await this.systemRepo.create(system, {
        currentUser: this.currentUser,
        transaction,
      })
      await transaction.commit()
      return system
    } catch (error) {
      await transaction.rollback()
      throw error
    }
  }
}

module.exports = CreateSystem
